package cn.rxls.community.service.impl;

import cn.rxls.community.dto.PageDTO;
import cn.rxls.community.dto.resourceUsage.ResourceUsagePageDTO;
import cn.rxls.community.entity.Houses;
import cn.rxls.community.entity.ResourceUsage;
import cn.rxls.community.entity.UserHouses;
import cn.rxls.community.enums.ResultEnum;
import cn.rxls.community.exception.BusinessException;
import cn.rxls.community.mapper.HousesMapper;
import cn.rxls.community.mapper.ResourceUsageMapper;
import cn.rxls.community.mapper.UserHousesMapper;
import cn.rxls.community.service.ResourceUsageService;
import cn.rxls.community.util.HttpUtil;
import cn.rxls.community.vo.resourceUsage.ResourceUsageVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 资源使用(ResourceUsage)表服务实现类
 *
 */
@Service("resourceUsageService")
public class ResourceUsageServiceImpl extends ServiceImpl<ResourceUsageMapper, ResourceUsage> implements ResourceUsageService {

    private final ResourceUsageMapper resourceUsageMapper;

    private final UserHousesMapper userHousesMapper;

    ResourceUsageServiceImpl(ResourceUsageMapper resourceUsageMapper, UserHousesMapper userHousesMapper) {
        this.resourceUsageMapper = resourceUsageMapper;
        this.userHousesMapper = userHousesMapper;
    }

    /**
     * 分页查询资源使用
     *
     * @param dto 参数对象
     * @return 多条信息
     */
    @Override
    public List<ResourceUsageVO> selectPageResourceUsageByHouseId(ResourceUsagePageDTO dto) {
        //获取用户id
        String uid = String.valueOf(HttpUtil.getUserLoginInfo().get("uid"));

        //查询此房屋是否属于该用户
        LambdaQueryWrapper<UserHouses> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserHouses::getHouseId, 1).eq(UserHouses::getUserId, Long.valueOf(uid)).eq(UserHouses::getState,1);
        List<UserHouses> userHouses = userHousesMapper.selectList(wrapper);
        List<UserHouses> collect = userHouses.stream().filter(s -> s.getHouseId().equals(dto.getHouseId())).collect(Collectors.toList());
        if (collect.size() < 1) {
            throw new BusinessException(ResultEnum.ERROR_HOUSE_USER);
        }

        dto.setPage((dto.getPage() - 1) * dto.getSize());
        ResourceUsage resourceUsage = new ResourceUsage();
        resourceUsage.setHouseId(dto.getHouseId());
        return resourceUsageMapper.selectPageResourceUsage(dto.getPage(), dto.getSize(), resourceUsage);
    }
}

